<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2016/11/29
 * Time: 18:18
 */

require 'env.php';
require 'pdo.php';
require 'ExcleReader.php';

$file = $_FILES["excelfile"];

$max_size = "20000000"; //最大文件限制（单位：byte）
$fname = $file['name'];
$types = ['xls', 'xlsx', 'csv'];
$ftype = strtolower(substr(strrchr($fname, '.'), 1));
//文件格式
$uploadfile = $file['tmp_name'];

if (is_uploaded_file($uploadfile)) {
    if ($file['size'] > $max_size) {
        $ms = $max_size / 1024 / 1024;
        exit("导入文件太大，不能超过" . $ms . 'M');
    }

    if (!in_array($ftype, $types)) {
        exit("文件类型错误");
    }

} else {
    exit("文件为空");
}


function getCsvc($filen)
{
    $file = fopen($filen, 'r');
    while ($data = fgetcsv($file)) { //每次读取CSV里面的一行内容
        $lists[] = $data;
    }
    fclose($file);
    return $lists;
}

$file_arr = getCsvc($uploadfile);
unset($file_arr[0]);
$res = save_data($file_arr);
if ($res) {
    echo '导入成功，请过24小时前往下载页面下载状态表';
}


function save_data($data)
{
    foreach ($data as $d) {
        $new_data['num'] = $d[0];
        $new_data['createtime'] = date('Y-m-d H:i:s');
        $newDatas[] = $new_data;
    }

    $result = mysql_mulit_insert('id_nums', $newDatas);
    return $result;

}


function mysql_mulit_insert($table, $arrData)
{
    try {
        $dsn = 'mysql:dbname=' . DB_NAME . ';host=' . DB_HOST . ';port=' . DB_PORT;
        $user = DB_USER;
        $password = DB_PWD;
        $dbh = new PDO($dsn, $user, $password);
        $dbh->query("set names utf8");
        $name = $values = '';
        $flag = $flagV = 1;
        $true = is_array(current($arrData));//判断是否一次插入多条数据
        if ($true) {
            //构建插入多条数据的sql语句
            foreach ($arrData as $arr) {

                $values .= $flag ? '(' : ',(';
                foreach ($arr as $key => $value) {
                    if ($flagV) {
                        if ($flag) $name .= "$key";
                        $values .= "'$value'";
                        $flagV = 0;
                    } else {
                        if ($flag) $name .= ",$key";
                        $values .= ",'$value'";
                    }
                }
                $values .= ') ';
                $flag = 0;
                $flagV = 1;
            }
        } else {
            //构建插入单条数据的sql语句
            foreach ($arrData as $key => $value) {
                if ($flagV) {
                    $name = "$key";
                    $values = "('$value'";
                    $flagV = 0;
                } else {
                    $name .= ",$key";
                    $values .= ",'$value'";
                }
            }
            $values .= ") ";
        }

        $strSql = "replace into $table ($name) values $values";

        $ret = $dbh->exec($strSql);
        return $ret;
    } catch (Exception $e) {
        echo $e->getMessage();
    }

}